package com.zsg.androidsipphone.sip;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.sip.SipAudioCall;
import android.net.sip.SipProfile;
import com.zsg.androidsipphone.MainActivity;

/**
 * @author zsg
 * @date 2020/9/8
 */
public class IncomingCallReceiver extends BroadcastReceiver {
    /**
     * 处理来电，接听电话，并将其交给 SipActivity
     * @param context 上下文
     * @param intent intent.
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        SipAudioCall incomingCall = null;
        try {
            SipAudioCall.Listener listener = new SipAudioCall.Listener() {
                @Override
                public void onRinging(SipAudioCall call, SipProfile caller) {
                    try {
                        call.answerCall(30);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            //takeAudioCall就表示需要为接听电话创建一个SipAudioCall对象.
            MainActivity mainActivity = (MainActivity) context;
            incomingCall = mainActivity.manager.takeAudioCall(intent, listener);
            incomingCall.answerCall(30);
            incomingCall.startAudio();
            incomingCall.setSpeakerMode(true);
            if(incomingCall.isMuted()) {
                incomingCall.toggleMute();
            }
        } catch (Exception e) {
            if (incomingCall != null) {
                incomingCall.close();
            }
        }
    }

}
